package com.wan.net.handler.client;

import com.wan.net.core.packet.Packet;
import com.wan.net.session.AttributeKeys;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

@ChannelHandler.Sharable
public abstract class AbstractClientChannelHandler extends SimpleChannelInboundHandler<Packet> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 连接channel激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Channel channel = ctx.channel();
        CountDownLatch latch = AttributeKeys.getOrSet(channel,AttributeKeys.SIGNAL,()->new CountDownLatch(1));
        latch.countDown();
    }

    /**
     * 连接正常断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    /**
     * 事件触发
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            logger.error("客户端连接空闲超时...channel={}",ctx.channel());
            ctx.close();
        }
    }

    /**
     * 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("连接异常...channel={}", ctx.channel(),cause);
        ctx.close();
    }
}
